import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {
    View,
    StyleSheet,
    ViewPropTypes,
    Text,
    Image,
    ImageBackground,
    TouchableOpacity,
} from 'react-native';
import Dialog from '@greens/onion/src/dialog';
import systemModule from '@greens/onion/src/system';
import IImage, {ImageType} from '../image/'
import Data from "@greens/utils/src/data";
import Device from "@greens/device/src/device";

export default class ImageBoxS3 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isInternalUpdate: false
        }
    }

    static getDerivedStateFromProps(props, state) {
        // console.log("DerivedStateFromProps:"+JSON.stringify(props))
        //console.log("DerivedStateFromState:"+JSON.stringify(state))
        if (state.isInternalUpdate) {
            return state;
        }
        return props;
    }

    setImage = (data) => {
        if (data != undefined && data != null) {
            if (this.props.onImageChange) {
                this.props.onImageChange(data, this.props.tag)
            } else {
                this.setState({dataSource: data, isInternalUpdate: true})
                this.state.isInternalUpdate = false;
            }
        } else {
            Dialog.showFailedToast('图片无效,请重新选择!');
        }
    }

    pickImage = () => {
        if (this.props.onPickSourceEvent) {
            this.props.onPickSourceEvent(parseInt(this.props.tag), (data) => {
                this.setImage(data)
            })
        }
    }

    cleanImage = () => {
        this.setImage({url: ""})
    }

    clickImage = () => {
        if (this.props.onPreviewClick) {
			let fileType = FileType.image;
			if (this.isVideo()) {
				fileType = FileType.video;
			} else if (this.isPdf()) {
				fileType = FileType.pdf;
			}
			this.props.onPreviewClick(fileType, this.props.dataSource.url)
		} else {
			if (this.isVideo()) {
				systemModule.playVideo({
					url: this.props.dataSource.url
				});
			} else if (this.isPdf()) {
				systemModule.showPDF(this.props.dataSource.url)
			} else if (this.isImage()) {
				systemModule.showPhoto({
					photoUrls: [this.props.dataSource.url]
				})
			} else {
				if (Data.isEmpty(this.props.dataSource.url)) return;
				systemModule.showPhoto({
					photoUrls: [this.props.dataSource.url]
				})
			}
		}
    }

    whatType = (fileUrl) => {
        let strings = fileUrl ? fileUrl.split('.') : null;
        if (strings && strings.length > 0 && fileUrl != "add") {
            let type = strings[strings.length - 1];
            if (type == "jpg" || type == "jpeg" || type == "png" || type == "gif" || type == "jpg".toUpperCase() || type == "png".toUpperCase()) {
                return FileType.image;
            } else if (type == "mp4" || type == "avi" || type == "mov" || type == "wmv" || type == "mp4".toUpperCase()) {
                return FileType.video;
            } else if (type == "mp3" || type == "aac" || type == "mav") {
                return FileType.audio;
            } else if (type == "pdf" || type == "pdf".toUpperCase()) {
                return FileType.pdf;
            } else {
                return FileType.unkown;
            }
        } else {
            return FileType.none;
        }
    }

    isVideo = () => {
        return this.whatType(this.state.dataSource.url) == FileType.video;
    }

    isPdf = () => {
        return this.whatType(this.state.dataSource.url) == FileType.pdf;
    }

    isImage = () => {
        return this.whatType(this.state.dataSource.url) == FileType.image;
    }

    isNone = () => {
        return this.whatType(this.state.dataSource.url) == FileType.none;
    }

    getSurface = () => {
        if (this.isVideo()) {
            return require("./video_bg.png")
        } else if (this.isPdf()) {
            return require("./icon_pdf.png")
        } else {
            return this.state.dataSource.url;
        }
    }

    renderBox = () => {
        if (this.props.isImageReadOnly) {
            return (
                <View style={{flex: 1}}>
                    <TouchableOpacity style={{flex: 1}} onPress={this.clickImage}>
                        <IImage
                            placeholderImage={require('./place_img.png')}
                            style={[styles.imageStyle, this.props.imageStyle, {
                                width: this.props.style.width,
                                height: this.props.height,
                                overflow: 'hidden'
                            }]}
                            source={this.getSurface()}
                            type={ImageType.custom}
                            resizeMode={'cover'}/>
                        {
                            this.isVideo() ? <View style={{
                                position: 'absolute',
                                justifyContent: 'center',
                                alignItems: 'center',
                                backgroundColor: 'rgba(0,0,0,0)',
                                left: 0,
                                right: 0,
                                top: 0,
                                bottom: 0
                            }}>
                                <Image source={require('./icon_play.png')}/>
                            </View> : null
                        }
                        {/*{*/}
                        {/*    this.isPdf() ?<View style={{position:'absolute',justifyContent:'center',alignItems:'center',left:0,right:0,top:0,bottom:0}}>*/}
                        {/*        <Image source={require('./icon_pdf.png')}/>*/}
                        {/*    </View>:null*/}
                        {/*}*/}
                    </TouchableOpacity>
                </View>
            );
        } else {
            if (this.state.dataSource && !Data.isEmpty(this.state.dataSource.url) && !this.isNone()) {
                return (
                    <View style={{flex: 1}}>
                        <TouchableOpacity style={{flex: 1}} onPress={this.clickImage}>
                            <IImage
                                style={[styles.imageStyle, this.props.imageStyle, {
                                    width: this.props.style.width,
                                    height: this.props.height,
                                    overflow: 'hidden'
                                }]}
                                placeholderImage={require('./place_img.png')}
                                source={this.getSurface()}
                                type={ImageType.custom}
                                resizeMode={'cover'}/>
                            {
                                this.isVideo() ? <View style={{
                                    position: 'absolute',
                                    justifyContent: 'center',
                                    alignItems: 'center',
                                    backgroundColor: 'rgba(0,0,0,0)',
                                    left: 0,
                                    right: 0,
                                    top: 0,
                                    bottom: 0
                                }}>
                                    <Image source={require('./icon_play.png')}/>
                                </View> : null
                            }
                            {/*{*/}
                            {/*    this.isPdf() ?<View style={{position:'absolute',justifyContent:'center',alignItems:'center',left:0,right:0,top:0,bottom:0}}>*/}
                            {/*        <Image source={require('./icon_pdf.png')}/>*/}
                            {/*    </View>:null*/}
                            {/*}*/}
                        </TouchableOpacity>
                        <View style={{
                            backgroundColor: 'rgba(0,0,0,0.5)',
                            position: 'absolute',
                            flexDirection: 'row',
                            width: this.props.style.width - 1,
                            height: this.props.style.height * 0.3,
                            marginTop: this.props.style.height * 0.7,
                            borderBottomLeftRadius: 3,
                            borderBottomRightRadius: 3,
                        }}>
                            <TouchableOpacity style={{flex: 1}} onPress={this.cleanImage}>
                                <View style={{alignItems: 'center', justifyContent: 'center', flex: 1}}>
                                    <Text style={[styles.editDeleteStyle, this.props.deleteTextStyle]}>删除</Text>
                                </View>
                            </TouchableOpacity>
                            <View style={{
                                width: 0.5,
                                height: this.props.style.height * 0.3,
                                backgroundColor: 'rgba(255,255,255,0.3)'
                            }}/>
                            <TouchableOpacity style={{flex: 1}} onPress={this.pickImage}>
                                <View style={{alignItems: 'center', justifyContent: 'center', flex: 1}}>
                                    <Text style={[styles.editModifyStyle, this.props.modifyTextStyle]}>修改</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                );
            } else {
                return (
                    <View style={{flex: 1}}>
                        <TouchableOpacity style={{flex: 1}} onPress={this.pickImage}>
                            <ImageBackground style={styles.imageStyle}>
                                <Image source={require('./gray_cross.png')}/>
                            </ImageBackground>
                        </TouchableOpacity>
                    </View>
                );
            }
        }
    }

    render() {
        return (
            <View style={this.props.style}>
                {
                    this.renderBox()
                }
            </View>
        );
    }
}

const styles = StyleSheet.create({
    imageStyle: {
        borderRadius: 3,
        backgroundColor: '#F6F6F6',
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    editDeleteStyle: {
        color: '#FFFFFF',
        fontSize: 14,
        alignSelf: 'center',
    },
    editModifyStyle: {
        color: '#FFFFFF',
        fontSize: 14,
        alignSelf: 'center',
    }
});

ImageBoxS3.propTypes = {
    style: ViewPropTypes.style,
    imageStyle: ViewPropTypes.style,
    deleteTextStyle: Text.propTypes.style,
    modifyTextStyle: Text.propTypes.style,
    dataSource: PropTypes.object,
    imagePickDialog: PropTypes.object,
    onImageChange: PropTypes.func, ///变动事件
    tag: PropTypes.string, ///控件TAG
    isImageReadOnly: PropTypes.bool, ///是否只能展示图片，不支持增删交互。
    onPickSourceEvent: PropTypes.func,
    onPreviewClick: PropTypes.func,
}

ImageBoxS3.defaultProps = {
    style: {
        width: (Device.SCREEN_WIDTH - 60) / 2,
        height: (Device.SCREEN_WIDTH - 60) / 2 * 0.762,
        borderRadius: 5,
        borderColor: '#EEEEEE',
        borderWidth: 1,
    },
    isImageReadOnly: false,
}

export const FileType = {
    none: 0,
    image: 1,
    video: 2,
    audio: 3,
    pdf: 4,
    unkown: 5
}
